package com.p2p.base.redis;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.p2p.base.cache.Cache;


public class RedisClientImpl implements Cache{

	@Resource
	private RedisTemplate<String,Object> businessRedisTemplate;
	
//	public void add(String key,Object value) {
//		ValueOperations<String,Object> valueops = businessRedisTemplate
//				.opsForValue();
//		valueops.set(key, value);
//	}
	
	public RedisTemplate<String, Object> getBusinessRedisTemplate() {
		return businessRedisTemplate;
	}


	public void setBusinessRedisTemplate(
			RedisTemplate<String, Object> businessRedisTemplate) {
		this.businessRedisTemplate = businessRedisTemplate;
	}


	public void add(String key, Object value, long timeout, TimeUnit unit) {
		ValueOperations<String,Object> valueops = businessRedisTemplate
				.opsForValue();
		valueops.set(key, value,timeout,unit);
	}

	
	public Object getValue(String key) {
		ValueOperations<String, Object> valueops = businessRedisTemplate
				.opsForValue();
		Object value = valueops.get(key);
		return value;
	}

	public void delete(String key) {
		businessRedisTemplate.delete(key);
	}
	
	/**
	 * 批量删除
	 */
	public void delete(Collection<String> keys) {
		businessRedisTemplate.delete(keys);
	}

	public Boolean exists(String key) {
		return businessRedisTemplate.hasKey(key);
	}

	//如果这个key不在redis中，就设置，并缓存一段时间。
	//TODO 问题，如果setIfAbsent执行之后，没有设置过期时间，且此时，服务器挂了，那么后面的设置缓存时间就失败了，然后这个key一直缓存在redis中。
	public boolean setIfAbsent(String key, Object value, long timeout){
		ValueOperations<String, Object> valueops = businessRedisTemplate
				.opsForValue();
		boolean result = valueops.setIfAbsent(key, value);
		if(result){
			this.add(key, value, timeout, TimeUnit.SECONDS);
		}
		return result;
	}

	@Override
	public Map<String, Object> getMulti(List<String> keys) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object[] getMulti(String[] keys) {
		// TODO Auto-generated method stub
		ValueOperations<String, Object> valueops = businessRedisTemplate
				.opsForValue();
		List<String> keys_list = Arrays.asList(keys);
		List<Object> value = valueops.multiGet(keys_list);
		return value.toArray();
	}

	@Override
	public void add(String key, Object value, long timeout) {
		ValueOperations<String,Object> valueops = businessRedisTemplate
				.opsForValue();
		valueops.set(key, value,timeout,TimeUnit.SECONDS);
	}
}
